package cate.game.server.configuration.part;

import cp.solution.business.cloud.CloudMongoEntity;
import easy.mongo.core.MgCli;
import easy.mongo.core.MgCnf;
import easy.mongo.core.MgParam;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class MgCliPool {

    private static boolean shareClientMode = true;

    public static MgCliPool instance = new MgCliPool();

    public synchronized MgCli get(CloudMongoEntity mongo) {
        return shareClientMode ? getShare(mongo) : getIsolate(mongo);
    }

    private int cliCreateTimes = 0;

    private Map<String, MgCli> shareCliMap = new HashMap<>(1);
    private MgCli getShare(CloudMongoEntity mongo) {
        MgCli cli = shareCliMap.get(mongo.getCode());
        if(cli == null) {
            cliCreateTimes++;
            log.info("第{}次创建Mongo客户端 cloudMongo.code={}", cliCreateTimes, mongo.getCode());
            MgCnf cnf = new MgCnf().setMode(mongo.getMode()).setHost(mongo.getHost()).setPort(mongo.getPort())
                    .setUsername(mongo.getUsername()).setPassword(mongo.getPassword()).setSource(mongo.getSource())
                    .setUrl(mongo.getUrl());
            MgParam p = MgParam.getDefault();
            p.connectionPool.minSize = 2;
            p.connectionPool.maxSize = 8;
            cli = new MgCli().setup(cnf, p);
            shareCliMap.put(mongo.getCode(), cli);
        }
        return cli;
    }

    private MgCli getIsolate(CloudMongoEntity mongo) {
        cliCreateTimes++;
        log.info("第{}次创建Mongo客户端 cloudMongo.code={}", cliCreateTimes, mongo.getCode());
        MgCnf cnf = new MgCnf().setMode(mongo.getMode()).setHost(mongo.getHost()).setPort(mongo.getPort())
                .setUsername(mongo.getUsername()).setPassword(mongo.getPassword()).setSource(mongo.getSource())
                .setUrl(mongo.getUrl());
        MgParam p = MgParam.getDefault();
        p.connectionPool.minSize = 1;
        p.connectionPool.maxSize = 1;
        MgCli mc = new MgCli().setup(cnf, p);
        return mc;
    }
}
